﻿using AutoMapper;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using Ross.EntityFramework;
using Ross.EntityFramework.Model;
using Ross.Service.Dto;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace Ross.Service
{
    public class BSCReports_DpService : BaseService, IDisposable
    {
        private TranDbContext dbContext;
        public IRepository<Targets, int> repository_T;
        public IRepository<History, int> repository_H;
        private TargetService targetService;
        public BSCReports_DpService(string nameOrConnectionString)
        {
            dbContext = new TranDbContext(nameOrConnectionString);
            repository_T = new Repository<Targets, int>(dbContext);
            repository_H = new Repository<History, int>(dbContext);
            targetService = new TargetService(nameOrConnectionString);
        }

        public void Dispose()
        {
            dbContext.Dispose();
        }

        public ResultDto<List<Dto.BSCReports_Co>> GetTreeList(string version = "")
        {
            ResultDto<List<Dto.BSCReports_Co>> result = new ResultDto<List<Dto.BSCReports_Co>>();
            var lists_t = new List<Targets>();
            var lists_h = new List<History>();
            if (!string.IsNullOrEmpty(version))
            {
                lists_h = repository_H.GetAllList(o => o.Version == version).ToList();
                var resp = GetTargetsTree_H(lists_h);
                var tree = resp.Where(o => o.TargetName == year.ToString()).ToList();
                if (tree.Count > 0)
                    result.datas = tree;
                else
                    result.message = $"未查询到{year}年数据";
            }
            else
            {
                lists_t = repository_T.GetAllList(o => o.ApprovalStatus == "已审核").ToList();
                var resp = GetTargetsTree_T(lists_t);
                var tree = resp.Where(o => o.TargetName == year.ToString()).ToList();
                if (tree.Count > 0)
                    result.datas = tree;
                else
                    result.message = $"未查询到{year}年数据";
            }
            return result;
        }

        /// <summary>
        /// 创建目标任务树
        /// </summary>
        /// <param name="datas"></param>
        /// <param name="parentid"></param>
        /// <returns></returns>
        private List<Dto.BSCReports_Co> GetTargetsTree_T(List<Targets> datas, int parentid = -1)
        {
            List<Dto.BSCReports_Co> result = new List<Dto.BSCReports_Co>();
            var lists = datas.Where(o => o.ParentTargetID == parentid).ToList();
            foreach (var item in lists)
            {
                Dto.BSCReports_Co obj = new Dto.BSCReports_Co();
                obj = Mapper.Map<Dto.BSCReports_Co>(item);
                var childrens = datas.Where(o => o.ParentTargetID == item.ID).ToList();
                if (childrens.Count > 0)
                {
                    obj.Child = GetTargetsTree_T(datas, item.ID);
                }
                result.Add(obj);
            }
            return result;
        }

        /// <summary>
        /// 创建目标任务树
        /// </summary>
        /// <param name="datas"></param>
        /// <param name="parentid"></param>
        /// <returns></returns>
        private List<Dto.BSCReports_Co> GetTargetsTree_H(List<History> datas, int parentid = -1)
        {
            List<Dto.BSCReports_Co> result = new List<Dto.BSCReports_Co>();
            var lists = datas.Where(o => o.ParentTargetID == parentid).ToList();
            foreach (var item in lists)
            {
                Dto.BSCReports_Co obj = new Dto.BSCReports_Co();
                obj = Mapper.Map<Dto.BSCReports_Co>(item);
                var childrens = datas.Where(o => o.ParentTargetID == item.ID).ToList();
                if (childrens.Count > 0)
                {
                    obj.Child = GetTargetsTree_H(datas, item.ID);
                }
                result.Add(obj);
            }
            return result;
        }
        /// <summary>
        /// 返回文件流供前端下载excel
        /// </summary>
        /// <returns></returns>
        public FileResult ExportExcel_Co(string ver="")
        {
            //ResultDto<FileResult> result = new ResultDto<FileResult>();
            try
            {
                HSSFWorkbook book = new HSSFWorkbook();
                ISheet sheet1 = book.CreateSheet("Sheet1");
                //设置列宽
                for (int i = 0; i < 20; i++)
                    sheet1.SetColumnWidth(i, 3000);
                //标题设置
                IRow row0 = sheet1.CreateRow(0);
                row0.HeightInPoints = 30;
                IFont fontTitle = book.CreateFont();
                fontTitle.FontHeightInPoints = 12;
                fontTitle.Boldweight = (short)FontBoldWeight.Bold;
                //设置单元格边框
                ICellStyle styleTiltle = book.CreateCellStyle();
                styleTiltle.Alignment = HorizontalAlignment.Center;
                styleTiltle.SetFont(fontTitle);
                styleTiltle.VerticalAlignment = VerticalAlignment.Center;
                IFont fontContent = book.CreateFont();
                fontContent.FontHeightInPoints = 12;
                ICellStyle styleContent = book.CreateCellStyle();
                styleContent.Alignment = HorizontalAlignment.Center;
                styleContent.SetFont(fontContent);
                styleContent.VerticalAlignment = VerticalAlignment.Center;
                string currxzq = "BSC报表-公司级";
                row0.CreateCell(0).SetCellValue(currxzq);
                sheet1.AddMergedRegion(new CellRangeAddress(0, 0, 0, 4));
                row0.GetCell(0).CellStyle = styleTiltle;
                IRow rowhead = sheet1.CreateRow(1);
                string[] colums = ("分类|战略目标|目标分解|责任部门").Split('|');
                for (int i = 0; i < colums.Length; i++)
                {
                    if(i==2)
                    {
                        rowhead.CreateCell(i).SetCellValue(colums[i]);
                        sheet1.AddMergedRegion(new CellRangeAddress(1, 1, 2, 3));
                        rowhead.GetCell(i).CellStyle = styleContent;
                    }
                    if (i == 3)
                    {
                        rowhead.CreateCell(i+1).SetCellValue(colums[i]);
                        sheet1.AddMergedRegion(new CellRangeAddress(1, 2, 4, 4));
                        rowhead.GetCell(i+1).CellStyle = styleContent;
                    }
                    else
                    {
                        rowhead.CreateCell(i).SetCellValue(colums[i]);
                        sheet1.AddMergedRegion(new CellRangeAddress(1, 2, i, i));
                        rowhead.GetCell(i).CellStyle = styleContent;
                    }

                }
                string[] colums2 = ("部门目标|考核基准").Split('|');
                IRow rowhead2 = sheet1.CreateRow(2);
                for (int i = 0; i < colums2.Length; i++)
                {
                    rowhead2.CreateCell(i+2).SetCellValue(colums2[i]);
                    sheet1.AddMergedRegion(new CellRangeAddress(2, 2, i+2, i+2));
                    rowhead2.GetCell(i+2).CellStyle = styleContent;
                }
                int RowNum = 3;
                //ResultDto<List<BSCReports_DpOut>> datas = new ResultDto<List<BSCReports_DpOut>>();
                var datas =TreeToList(GetTreeList(ver).datas);
                var depts = targetService.GetDeptAsync();
                
                if (datas.Count > 0)
                {
                    foreach (var zhanlue in datas)
                    {

                        IRow row = sheet1.CreateRow(RowNum);
                        row.CreateCell(0).SetCellValue(zhanlue.Classification);
                        row.CreateCell(1).SetCellValue(zhanlue.TargetName);
                        row.CreateCell(2).SetCellValue(zhanlue.TargetName);
                        row.CreateCell(3).SetCellValue(zhanlue.AssessmentCriteria);
                        var dp = depts.Where(o => o.DepartmentID == zhanlue.Department).ToList();
                        row.CreateCell(4).SetCellValue(dp[0].DepartmentName);
                        RowNum++;


                    }
                    MemoryStream ms = new MemoryStream();
                    book.Write(ms);
                    ms.Seek(0, SeekOrigin.Begin);
                    FileStreamResult file = new FileStreamResult(ms, "application/vnd.ms-excel");
                    file.FileDownloadName = "BSC总表报表" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".xls";
                    return file;
                }
            }
            catch (Exception e)
            {
                //result.status = 500;
                //result.message = e.Message;
            }
            return null;
        }

        public ResultDto<List<Dto.BSCReports_CoOut>> GetReports(string ver = "")
        {
            ResultDto<List<Dto.BSCReports_CoOut>> result = new ResultDto<List<Dto.BSCReports_CoOut>>();
            try
            {
                var datas = GetTreeList(ver).datas;
                if (datas.Count > 0)
                {
                    List<BSCReports_CoOut> list = new List<BSCReports_CoOut>();
                    list = TreeToList(datas);
                    result.datas = list;
                }
            }
            catch (Exception e)
            {
                result.status = 500;
                result.message = e.Message;
            }
            return result;
        }

        
        List<BSCReports_CoOut> TreeToList(List<Dto.BSCReports_Co> lists)
        {
            List<Dto.BSCReports_CoOut> result = new List<BSCReports_CoOut>();
            if (lists!=null)
            {
                foreach (var niandu in lists)
                {
                    if (niandu.Child != null)
                    {
                        foreach (var jiaodu in niandu.Child)
                        {
                            if (jiaodu.Child != null)
                            {
                                foreach (var zhanlue in jiaodu.Child)
                                {
                                    if (zhanlue.Child != null)
                                    {
                                        foreach (var bumen in zhanlue.Child)
                                        {
                                            BSCReports_CoOut obj = new BSCReports_CoOut()
                                            {
                                                Classification = jiaodu.TargetName,
                                                TargetName = zhanlue.TargetName,
                                                DepartmentTarget = bumen.TargetName,
                                                AssessmentCriteria = bumen.AssessmentCriteria,
                                                Department = bumen.Department
                                            };
                                            result.Add(obj);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return result;
        }
    }
}
